//
//  ImageSelectTools.m
//  YiLin
//
//  Created by Zyark on 2018/6/14.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ImageSelectTools.h"
#import "JDStatusBarNotification.h"
#import "GACompressionPicHandle.h"
#import "NSErrorHelper.h"
#import <TZImagePickerController.h>
#import <TZImageManager.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AFNetworking.h>

@interface ImageSelectTools()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>
@property(nonatomic,strong) NSData *postImageData;
@end

@implementation ImageSelectTools
//选择图片
-(void)alertSelectImage:(UIViewController *)vc{
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[language getStringByKey:LC_UPLOAD_PHOTO_ADD_IMAGE] message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:[language getStringByKey:LC_UPLOAD_PHOTO_ALBUM] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //        _isAddImage = NO;
        
        TZImagePickerController* albumPrickerController = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
        //        albumPrickerController.allowPickingOriginalPhoto = NO;
        albumPrickerController.allowPickingVideo = NO;
        albumPrickerController.navigationBar.barTintColor = kMainColor;
        albumPrickerController.needCircleCrop = YES;
        albumPrickerController.circleCropRadius = 100;
        [vc presentViewController:albumPrickerController animated:YES completion:nil];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:[language getStringByKey:LC_UPLOAD_IMAGE_CAMERA] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Device has no camera" preferredStyle:UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                return;
            }]];
            
            [vc presentViewController:alert animated:YES completion:nil];
        } else {
            UIImagePickerController *imagePickerController = [UIImagePickerController new];
            imagePickerController.delegate = self;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.allowsEditing = YES;
            imagePickerController.showsCameraControls = YES;
            imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            //            Typically NSString *requiredMediaType = (__bridge NSString *)kUTTypeImage;
            imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
            
            
            [vc presentViewController:imagePickerController animated:YES completion:nil];
        }
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:[language getStringByKey:LC_UPLOAD_PHOTO_CANCEL] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        return;
    }]];
    
    [vc presentViewController:alertController animated:YES completion:nil];
}

#pragma mark TZImagePickerController Delegate

- (void)imagePickerController:(TZImagePickerController *)picker
       didFinishPickingPhotos:(NSArray<UIImage *> *)photos
                 sourceAssets:(NSArray *)assets
        isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
                        infos:(NSArray<NSDictionary *> *)infos
{
    //    [[TZImageManager manager] getOriginalPhotoWithAsset:assets completion:^(UIImage *photo, NSDictionary *info) {
    //
    //    }];
    //只选择一张图片
    UIImage* image = photos[0];
    _postImageData = [self compressImage:image];
    
    @weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        [picker dismissViewControllerAnimated:NO completion:nil];
        @strongify(self);
        if([self.delegate respondsToSelector:@selector(imageSelectTools:selectImage:imageData:)]){
            [self.delegate imageSelectTools:self selectImage:image imageData:_postImageData];
        }
    });
}

///获得原始图片
- (UIImage *)getOriginalImageWithAsset:(PHAsset *)asset{
    __block UIImage *image = [[UIImage alloc] init];
    //获得原始图
    [[TZImageManager manager] getOriginalPhotoWithAsset:asset completion:^(UIImage *photo, NSDictionary *info) {
        image = photo;
    }];
    return image;
}

- (void)imagePickerControllerDidCancel:(TZImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIImagePickerController 回调函数

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    _postImageData = [self compressImage:image];
    @weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        @strongify(self);
        [picker dismissViewControllerAnimated:YES completion:nil];
        if([self.delegate respondsToSelector:@selector(imageSelectTools:selectImage:imageData:)]){
            [self.delegate imageSelectTools:self selectImage:image imageData:_postImageData];
        }
    });
    
    //如果是拍照的照片，则需要手动保存到本地，系统不会自动保存拍照成功后的照片
    //UIImageWriteToSavedPhotosAlbum(edit, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
//图片压缩
-(NSData *)compressImage:(UIImage *)image{
    NSData* compressionImageData = nil;
    NSData* sourceImageData = UIImagePNGRepresentation(image);
    if (sourceImageData.length > stand_size) {
        CGFloat sourceImage_W = CGImageGetWidth(image.CGImage);
        CGFloat sourceImage_H = CGImageGetHeight(image.CGImage);
        CGFloat tagerImage_W = 0;
        CGFloat tagerImage_H = 0;
        if (sourceImage_W > CompressionMax_W) {
            tagerImage_W = CompressionMax_W;
            CGFloat scale = sourceImage_W / sourceImage_H;
            tagerImage_H = tagerImage_W / scale;
        }else{
            tagerImage_W = sourceImage_W;
            tagerImage_H = sourceImage_H;
        }
        GACompressionPicHandle* compressPicHandle = [GACompressionPicHandle shareCompressionPicHandle];
        compressionImageData = [compressPicHandle imageByScalingAndCroppingForSize:(CGSizeMake(tagerImage_W, tagerImage_H)) image:image];
    }else{
        compressionImageData = sourceImageData;
    }
    return compressionImageData;
}
@end
